<template>
  <el-card>
    <div slot="header" class="clearfix">
      <el-button icon="el-icon-plus" size="small" type="primary" @click="addTm">
        添加
      </el-button>
    </div>
    <el-table
      v-loading="loading"
      :data="tableData"
      style="width: 100%"
      border
      class="trademark-tabel"
    >
      <el-table-column type="index" width="100" align="center" label="序号" />
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column prop="name" label="品牌LOGO" align="center">
        <template #default="{ row }">
          <img :src="row.logoUrl" alt="" class="logoImg" />
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作">
        <template #default="{ row }">
          <el-button
            icon="el-icon-edit"
            size="mini"
            type="primary"
            @click="editTm(row)"
          ></el-button>

          <el-button
            icon="el-icon-delete"
            size="mini"
            type="danger"
            slot="reference"
            @click="delTm(row.id)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.page"
      :page-sizes="[3, 5, 10, 15]"
      :page-size="100"
      layout=" prev, pager, next, jumper, sizes, total"
      :total="pagination.total"
    />

    <el-dialog
      :title="formData.id ? '编辑品牌' : '添加品牌'"
      :visible.sync="dialogVisible"
      top="0"
      @closed="dialogClsoe"
    >
      <el-form
        label-width="100px"
        size="mini"
        :model="formData"
        :rules="rules"
        ref="formIns"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="formData.tmName" />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="`${baseUrl}/admin/product/fileUpload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="formData.logoUrl"
              :src="formData.logoUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" size="small" @click="submitForm">
          确 定
        </el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
import {
  getTrademarkListApi,
  addTrademark,
  editTrademarkApi,
  delTrademarkApi
} from '@/api/product/trademarkApi'

export default {
  name: 'TrademarkList',
  data() {
    return {
      tableData: [],
      loading: false,
      dialogVisible: false,
      baseUrl: process.env.VUE_APP_BASE_API,
      // 表单数据
      formData: {
        tmName: '',
        logoUrl: '',
        id: 0
      },
      // 分页数据
      pagination: {
        page: 1,
        limit: 3,
        total: 0
      },
      // 表单校验
      rules: {
        tmName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' }
        ],
        logoUrl: [
          {
            required: true,
            message: '请上传品牌图片',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    pagination: {
      handler() {
        this.getTrademark()
      },
      deep: true
    }
  },
  mounted() {
    this.getTrademark()
  },
  methods: {
    async getTrademark() {
      // 封装请求数据的方法
      this.loading = true
      const res = await getTrademarkListApi(
        this.pagination.page,
        this.pagination.limit
      )
      this.loading = false
      // console.log(res)
      this.tableData = res.data.records
      this.pagination.total = res.data.total
    },
    // 图片上传成功
    handleAvatarSuccess(res, file) {
      this.formData.logoUrl = res.data
    },
    // 图片上传之前的验证
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 1

      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 1MB!')
        return false
      }
      return true
    },
    // 改变pageSize
    handleSizeChange(size) {
      this.pagination.limit = size
    },
    // 切换页码
    handleCurrentChange(page) {
      this.pagination.page = page
    },
    // 提交表单
    submitForm() {
      this.$refs.formIns.validate(async (valid) => {
        if (valid) {
          if (this.formData.id) {
            await editTrademarkApi(this.formData)
            this.$message.success('修改品牌成功')
          } else {
            await addTrademark(this.formData)
            this.$message.success('添加品牌成功')
          }
          this.dialogVisible = false
          this.getTrademark()
        }
      })
    },
    // 添加品牌
    addTm() {
      this.formData.logoUrl = ''
      this.formData.tmName = ''
      this.formData.id = 0
      this.dialogVisible = true
    },
    // 编辑品牌
    editTm(data) {
      this.formData.logoUrl = data.logoUrl
      this.formData.tmName = data.tmName
      this.formData.id = data.id
      this.dialogVisible = true
    },
    // 删除品牌
    async delTm(id) {
      if (!confirm('确定删除吗')) return
      await delTrademarkApi(id)
      this.$message.success('删除成功')
      this.getTrademark()
    },
    // 对话框关闭。清空数据
    dialogClsoe() {
      this.formData.logoUrl = ''
      this.formData.tmName = ''
      this.formData.id = 0
      this.$refs.formIns.resetFields()
    }
  }
}
</script>

<style scoped>
.logoImg {
  height: 100px;
}
.trademark-tabel {
  margin-bottom: 20px;
}
</style>
